<template>
  <div
    class="task-card"
    :class="taskCardClasses"
    @click="handleCardClick"
    @contextmenu="handleRightClick"
  >
    <!-- 任务选择 -->
    <div v-if="showSelection" class="task-selection">
      <el-checkbox
        :model-value="selected"
        @change="handleSelectionChange"
        @click.stop
      />
    </div>

    <!-- 任务指示器 -->
    <div class="task-indicator">
      <div class="task-number" :class="numberClass">
        {{ task.sequence }}
      </div>
      <div class="task-status-icon">
        <el-icon v-if="task.status === 'COMPLETED'" class="status-icon success">
          <CircleCheckFilled />
        </el-icon>
        <el-icon v-else-if="task.status === 'FAILED'" class="status-icon error">
          <CircleCloseFilled />
        </el-icon>
        <el-icon v-else-if="task.status === 'IN_PROGRESS'" class="status-icon progress rotating">
          <Loading />
        </el-icon>
        <el-icon v-else-if="task.status === 'CANCELLED'" class="status-icon cancelled">
          <Remove />
        </el-icon>
        <el-icon v-else class="status-icon pending">
          <Clock />
        </el-icon>
      </div>
    </div>

    <!-- 任务内容 -->
    <div class="task-content">
      <!-- 任务头部 -->
      <div class="task-header">
        <div class="task-title-area">
          <h4 class="task-title" :title="task.description">
            {{ task.description }}
          </h4>
          <div class="task-meta">
            <el-tag :type="getTypeColor(task.type)" size="small" class="type-tag">
              {{ formatTaskType(task.type) }}
            </el-tag>
            <el-tag :type="getAgentColor(task.agentType)" size="small" class="agent-tag">
              {{ formatAgentType(task.agentType) }}
            </el-tag>
          </div>
        </div>

        <!-- 任务操作按钮 -->
        <div v-if="allowModification" class="task-actions" @click.stop>
          <el-dropdown @command="handleAction" trigger="click">
            <el-button type="text" :icon="MoreFilled" class="action-button" size="small" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="view" :icon="View">查看详情</el-dropdown-item>
                <el-dropdown-item command="edit" :icon="Edit">编辑任务</el-dropdown-item>
                <el-dropdown-item command="duplicate" :icon="CopyDocument">复制任务</el-dropdown-item>
                <el-dropdown-item command="delete" :icon="Delete" divided>删除任务</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 任务详情（展开时显示） -->
      <transition name="slide-down">
        <div v-if="expanded" class="task-details">
          <!-- 任务描述 -->
          <div v-if="task.description" class="detail-section">
            <h5 class="detail-title">任务描述</h5>
            <p class="detail-content">{{ task.description }}</p>
          </div>

          <!-- 依赖关系 -->
          <div v-if="showDependencies && task.dependencies.length > 0" class="detail-section">
            <h5 class="detail-title">依赖任务</h5>
            <div class="dependency-list">
              <span
                v-for="depId in task.dependencies"
                :key="depId"
                class="dependency-tag"
                @click.stop="$emit('dependency-click', depId)"
              >
                任务 {{ getDependencySequence(depId) }}
              </span>
            </div>
          </div>

          <!-- 时间信息 -->
          <div class="detail-section">
            <h5 class="detail-title">时间信息</h5>
            <div class="time-info">
              <div class="time-item">
                <span class="time-label">预计时间:</span>
                <span class="time-value">{{ task.estimatedTime }}s</span>
              </div>
              <div v-if="task.actualTime" class="time-item">
                <span class="time-label">实际时间:</span>
                <span class="time-value">{{ task.actualTime }}s</span>
              </div>
              <div v-if="task.startedAt" class="time-item">
                <span class="time-label">开始时间:</span>
                <span class="time-value">{{ formatTime(task.startedAt) }}</span>
              </div>
              <div v-if="task.completedAt" class="time-item">
                <span class="time-label">完成时间:</span>
                <span class="time-value">{{ formatTime(task.completedAt) }}</span>
              </div>
            </div>
          </div>

          <!-- 执行结果 -->
          <div v-if="task.result" class="detail-section">
            <h5 class="detail-title">执行结果</h5>
            <div class="result-content">
              <div class="result-text">{{ task.result.content }}</div>
              <div v-if="task.result.confidence" class="result-confidence">
                <span class="confidence-label">置信度:</span>
                <el-progress
                  :percentage="Math.round(task.result.confidence * 100)"
                  :stroke-width="4"
                  :show-text="false"
                  class="confidence-bar"
                />
                <span class="confidence-value">{{ Math.round(task.result.confidence * 100) }}%</span>
              </div>
            </div>
          </div>

          <!-- 错误信息 -->
          <div v-if="task.error" class="detail-section">
            <h5 class="detail-title error-title">错误信息</h5>
            <div class="error-content">
              <div class="error-message">{{ task.error.message }}</div>
              <div v-if="task.error.details" class="error-details">
                <el-collapse>
                  <el-collapse-item title="详细信息" name="details">
                    <pre>{{ JSON.stringify(task.error.details, null, 2) }}</pre>
                  </el-collapse-item>
                </el-collapse>
              </div>
              <div v-if="task.error.retryable" class="error-actions">
                <el-button type="primary" size="small" @click="$emit('retry', task.id)">
                  重试
                </el-button>
              </div>
            </div>
          </div>

          <!-- MCP服务调用 -->
          <div v-if="task.mcpServices && task.mcpServices.length > 0" class="detail-section">
            <h5 class="detail-title">MCP服务调用</h5>
            <div class="mcp-services">
              <div
                v-for="service in task.mcpServices"
                :key="`${service.serviceId}-${service.callTime}`"
                class="mcp-service-item"
              >
                <div class="service-info">
                  <span class="service-id">{{ service.serviceId }}</span>
                  <span class="service-method">{{ service.method }}</span>
                </div>
                <div class="service-time">
                  <span v-if="service.responseTime">{{ service.responseTime }}ms</span>
                  <span class="call-time">{{ formatTime(new Date(service.callTime)) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </transition>

      <!-- 任务进度条（进行中时显示） -->
      <div v-if="task.status === 'IN_PROGRESS'" class="task-progress">
        <el-progress
          :percentage="task.progress"
          :status="task.progress === 100 ? 'success' : undefined"
          :stroke-width="6"
          :show-text="false"
        />
        <span class="progress-text">{{ task.progress }}%</span>
      </div>
    </div>

    <!-- 展开/折叠按钮 -->
    <div class="expand-button" @click.stop="toggleExpanded">
      <el-icon :class="{ 'rotate-180': expanded }">
        <ArrowDown />
      </el-icon>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Task } from '@/types'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

// Props
interface Props {
  task: Task
  selected?: boolean
  viewMode?: 'list' | 'card'
  showDependencies?: boolean
  allowModification?: boolean
  showSelection?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  selected: false,
  viewMode: 'card',
  showDependencies: true,
  allowModification: true,
  showSelection: false
})

// Emits
interface Emits {
  select: [taskId: string, selected: boolean]
  action: [action: string, taskId: string]
  edit: [taskId: string]
  delete: [taskId: string]
  retry: [taskId: string]
  'dependency-click': [dependencyId: string]
}

const emit = defineEmits<Emits>()

// 状态
const expanded = ref(false)

// 计算属性
const taskCardClasses = computed(() => ({
  'task-card': true,
  [`task-card--${props.task.status.toLowerCase()}`]: true,
  [`task-card--${props.viewMode}`]: true,
  'task-card--selected': props.selected,
  'task-card--expanded': expanded.value,
  'task-card--clickable': !props.task.status || props.task.status !== 'IN_PROGRESS'
}))

const numberClass = computed(() => ({
  'task-number': true,
  [`task-number--${props.task.status.toLowerCase()}`]: true
}))

// 方法
const formatTaskType = (type: string) => {
  const typeMap: Record<string, string> = {
    RESEARCH: '研究',
    ANALYSIS: '分析',
    CALCULATION: '计算',
    REASONING: '推理',
    SYNTHESIS: '综合'
  }
  return typeMap[type] || type
}

const formatAgentType = (type: string) => {
  const agentMap: Record<string, string> = {
    GENERAL_QA: '通用',
    RESEARCH_SPECIALIST: '研究',
    MATH_SOLVER: '数学',
    LOGIC_REASONER: '逻辑'
  }
  return agentMap[type] || type
}

const getTypeColor = (type: string) => {
  switch (type) {
    case 'RESEARCH': return 'primary'
    case 'ANALYSIS': return 'success'
    case 'CALCULATION': return 'warning'
    case 'REASONING': return 'info'
    case 'SYNTHESIS': return 'danger'
    default: return 'info'
  }
}

const getAgentColor = (type: string) => {
  switch (type) {
    case 'GENERAL_QA': return 'info'
    case 'RESEARCH_SPECIALIST': return 'primary'
    case 'MATH_SOLVER': return 'warning'
    case 'LOGIC_REASONER': return 'success'
    default: return 'info'
  }
}

const formatTime = (date: Date) => {
  return formatDistanceToNow(date, {
    addSuffix: true,
    locale: zhCN
  })
}

const getDependencySequence = (depId: string) => {
  // 这里需要从store获取依赖任务的序号
  // 暂时返回ID的一部分
  return depId.slice(-4)
}

const handleCardClick = () => {
  if (props.task.status !== 'IN_PROGRESS') {
    toggleExpanded()
  }
}

const handleRightClick = (event: MouseEvent) => {
  event.preventDefault()
  // 可以在这里显示右键菜单
}

const handleSelectionChange = (selected: boolean) => {
  emit('select', props.task.id, selected)
}

const toggleExpanded = () => {
  expanded.value = !expanded.value
}

const handleAction = (command: string) => {
  switch (command) {
    case 'edit':
      emit('edit', props.task.id)
      break
    case 'delete':
      emit('delete', props.task.id)
      break
    default:
      emit('action', command, props.task.id)
  }
}
</script>

<style lang="scss" scoped>
.task-card {
  position: relative;
  background: var(--bg-color);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-base);
  transition: var(--transition-base);
  overflow: hidden;
  
  &.task-card--clickable {
    cursor: pointer;
    
    &:hover {
      border-color: var(--primary-color);
      box-shadow: var(--box-shadow-light);
      transform: translateY(-1px);
    }
  }
  
  &.task-card--selected {
    border-color: var(--primary-color);
    background: var(--primary-color-lighter);
  }
  
  &.task-card--expanded {
    .expand-button .el-icon {
      transform: rotate(180deg);
    }
  }
  
  // 状态样式
  &.task-card--pending {
    border-left: 4px solid var(--task-pending-color);
  }
  
  &.task-card--in_progress {
    border-left: 4px solid var(--task-progress-color);
    
    .task-content {
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 2px;
        background: linear-gradient(90deg, 
          var(--task-progress-color) 0%, 
          transparent 50%, 
          var(--task-progress-color) 100%);
        animation: progress-shimmer 2s infinite;
      }
    }
  }
  
  &.task-card--completed {
    border-left: 4px solid var(--task-success-color);
    opacity: 0.9;
  }
  
  &.task-card--failed {
    border-left: 4px solid var(--task-error-color);
  }
  
  &.task-card--cancelled {
    border-left: 4px solid var(--task-cancelled-color);
    opacity: 0.7;
  }
  
  // 视图模式
  &.task-card--list {
    margin-bottom: var(--spacing-sm);
    
    .task-content {
      padding: var(--spacing-sm) var(--spacing-md);
    }
    
    .task-indicator {
      .task-number {
        width: 24px;
        height: 24px;
        font-size: var(--font-size-small);
      }
    }
  }
  
  &.task-card--card {
    .task-content {
      padding: var(--spacing-md);
    }
  }
}

// 任务选择
.task-selection {
  position: absolute;
  top: var(--spacing-sm);
  left: var(--spacing-sm);
  z-index: var(--z-index-normal);
}

// 任务指示器
.task-indicator {
  position: absolute;
  top: var(--spacing-md);
  right: var(--spacing-md);
  @include flex-center;
  gap: var(--spacing-xs);
  z-index: var(--z-index-normal);
}

.task-number {
  @include flex-center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  font-weight: 600;
  font-size: var(--font-size-small);
  color: white;
  
  &.task-number--pending {
    background: var(--task-pending-color);
  }
  
  &.task-number--in_progress {
    background: var(--task-progress-color);
  }
  
  &.task-number--completed {
    background: var(--task-success-color);
  }
  
  &.task-number--failed {
    background: var(--task-error-color);
  }
  
  &.task-number--cancelled {
    background: var(--task-cancelled-color);
  }
}

.task-status-icon {
  font-size: 20px;
  
  .status-icon {
    &.success {
      color: var(--task-success-color);
    }
    
    &.error {
      color: var(--task-error-color);
    }
    
    &.progress {
      color: var(--task-progress-color);
      
      &.rotating {
        @include loading-animation;
      }
    }
    
    &.pending {
      color: var(--task-pending-color);
    }
    
    &.cancelled {
      color: var(--task-cancelled-color);
    }
  }
}

// 任务内容
.task-content {
  padding-right: 80px; // 为指示器留出空间
}

// 任务头部
.task-header {
  @include flex-between;
  margin-bottom: var(--spacing-sm);
}

.task-title-area {
  flex: 1;
  min-width: 0;
}

.task-title {
  @include text-ellipsis;
  margin: 0 0 var(--spacing-xs) 0;
  font-size: var(--font-size-base);
  font-weight: 600;
  color: var(--text-color-primary);
  line-height: 1.4;
}

.task-meta {
  @include flex-start;
  gap: var(--spacing-xs);
  flex-wrap: wrap;
}

.type-tag,
.agent-tag {
  font-size: var(--font-size-extra-small);
}

// 任务操作
.task-actions {
  flex-shrink: 0;
  margin-left: var(--spacing-sm);
}

.action-button {
  width: 24px;
  height: 24px;
  
  &:hover {
    background: var(--bg-color-light);
  }
}

// 任务详情
.task-details {
  margin-top: var(--spacing-md);
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--border-color-light);
}

.detail-section {
  margin-bottom: var(--spacing-md);
  
  &:last-child {
    margin-bottom: 0;
  }
}

.detail-title {
  margin: 0 0 var(--spacing-sm) 0;
  font-size: var(--font-size-small);
  font-weight: 600;
  color: var(--text-color-primary);
  
  &.error-title {
    color: var(--danger-color);
  }
}

.detail-content {
  margin: 0;
  font-size: var(--font-size-small);
  color: var(--text-color-secondary);
  line-height: 1.5;
}

// 依赖关系
.dependency-list {
  @include flex-start;
  gap: var(--spacing-xs);
  flex-wrap: wrap;
}

.dependency-tag {
  padding: 2px 6px;
  background: var(--primary-color-lighter);
  color: var(--primary-color);
  border-radius: var(--border-radius-small);
  font-size: var(--font-size-extra-small);
  cursor: pointer;
  transition: var(--transition-base);
  
  &:hover {
    background: var(--primary-color);
    color: white;
  }
}

// 时间信息
.time-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: var(--spacing-xs);
}

.time-item {
  @include flex-between;
  font-size: var(--font-size-small);
}

.time-label {
  color: var(--text-color-secondary);
}

.time-value {
  color: var(--text-color-primary);
  font-weight: 500;
}

// 执行结果
.result-content {
  .result-text {
    font-size: var(--font-size-small);
    color: var(--text-color-secondary);
    margin-bottom: var(--spacing-sm);
    line-height: 1.5;
  }
  
  .result-confidence {
    @include flex-center;
    gap: var(--spacing-sm);
    font-size: var(--font-size-small);
    
    .confidence-bar {
      flex: 1;
      max-width: 100px;
    }
    
    .confidence-value {
      font-weight: 600;
      color: var(--success-color);
    }
  }
}

// 错误信息
.error-content {
  .error-message {
    font-size: var(--font-size-small);
    color: var(--danger-color);
    margin-bottom: var(--spacing-sm);
    line-height: 1.5;
  }
  
  .error-details {
    margin-bottom: var(--spacing-sm);
    
    pre {
      background: var(--bg-color-dark);
      padding: var(--spacing-sm);
      border-radius: var(--border-radius-base);
      font-size: var(--font-size-extra-small);
      overflow-x: auto;
      color: var(--danger-color);
    }
  }
  
  .error-actions {
    @include flex-start;
  }
}

// MCP服务
.mcp-services {
  .mcp-service-item {
    @include flex-between;
    padding: var(--spacing-xs) var(--spacing-sm);
    background: var(--bg-color-light);
    border-radius: var(--border-radius-base);
    margin-bottom: var(--spacing-xs);
    font-size: var(--font-size-small);
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .service-info {
    @include flex-start;
    gap: var(--spacing-sm);
    
    .service-id {
      font-weight: 600;
      color: var(--primary-color);
    }
    
    .service-method {
      color: var(--text-color-secondary);
    }
  }
  
  .service-time {
    @include flex-end;
    gap: var(--spacing-sm);
    font-size: var(--font-size-extra-small);
    color: var(--text-color-placeholder);
  }
}

// 任务进度
.task-progress {
  @include flex-between;
  margin-top: var(--spacing-md);
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--border-color-light);
  
  .progress-text {
    font-size: var(--font-size-small);
    font-weight: 600;
    color: var(--task-progress-color);
    margin-left: var(--spacing-sm);
  }
}

// 展开按钮
.expand-button {
  position: absolute;
  bottom: var(--spacing-sm);
  right: var(--spacing-sm);
  width: 24px;
  height: 24px;
  @include flex-center;
  background: var(--bg-color-light);
  border: 1px solid var(--border-color);
  border-radius: 50%;
  cursor: pointer;
  transition: var(--transition-base);
  
  &:hover {
    background: var(--primary-color-lighter);
    border-color: var(--primary-color);
    
    .el-icon {
      color: var(--primary-color);
    }
  }
  
  .el-icon {
    transition: var(--transition-base);
    
    &.rotate-180 {
      transform: rotate(180deg);
    }
  }
}

// 动画
@keyframes progress-shimmer {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}

.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.slide-down-enter-from,
.slide-down-leave-to {
  opacity: 0;
  max-height: 0;
  padding-top: 0;
  margin-top: 0;
}

.slide-down-enter-to,
.slide-down-leave-from {
  opacity: 1;
  max-height: 500px;
}

// 响应式适配
@include respond-to(md) {
  .task-card {
    &.task-card--card {
      .task-content {
        padding: var(--spacing-sm);
        padding-right: 70px;
      }
    }
  }
  
  .task-indicator {
    top: var(--spacing-sm);
    right: var(--spacing-sm);
    
    .task-number {
      width: 28px;
      height: 28px;
      font-size: var(--font-size-extra-small);
    }
  }
  
  .task-meta {
    flex-direction: column;
    gap: var(--spacing-xs);
  }
  
  .time-info {
    grid-template-columns: 1fr;
  }
}

// 暗色主题
@include dark-theme {
  .task-card {
    background: var(--bg-color-dark);
    border-color: var(--border-color);
    
    &.task-card--selected {
      background: rgba(64, 158, 255, 0.1);
    }
  }
  
  .expand-button {
    background: var(--bg-color);
    border-color: var(--border-color);
  }
  
  .mcp-services .mcp-service-item {
    background: var(--bg-color);
  }
}
</style>